#!/bin/sh

if [ "$(command id -u)" = '0' ]; then
  echo 'running as root, which may uninstall any version; skipping'
  exit 0
fi

TMP_DIR=''
cleanup () {
  if [ -n "${TMP_DIR}" ] && [ -d "${TMP_DIR}/nvm/versions/node" ]; then
    chmod u+w "${TMP_DIR}/nvm/versions/node"
  fi
  case "${TMP_DIR}" in
    /*) rm -rf "${TMP_DIR}" ;;
  esac
}

die () { echo "$@" ; cleanup ; exit 1; }

TMP_DIR="$(mktemp -d)" || die 'could not create a temporary directory'

unset NVM_DEBUG
NVM_DIR="${TMP_DIR}/nvm"
export NVM_DIR
mkdir -p "${NVM_DIR}/alias" || die 'could not create alias dir'

: nvm.sh
\. ../../../nvm.sh
\. ../../common.sh

make_fake_node v20.1.1 || die 'could not make fake node v20.1.1'
make_fake_node v22.1.0 || die 'could not make fake node v22.1.0'
nvm_make_alias one v20.1.1 || die 'could not create alias one'
nvm_make_alias two v22.1.0 || die 'could not create alias two'

# the version's contents can be deleted, but not its directory
chmod a-w "${NVM_DIR}/versions/node" || die 'could not make versions dir read-only'

OUTPUT="$(set +x; nvm uninstall v20.1.1 2>"${TMP_DIR}/stderr")" && STATUS=0 || STATUS=$?
[ "${STATUS}" -eq 1 ] || die "expected uninstall to fail; got status ${STATUS}, output: ${OUTPUT}"
command grep -F -q 'Failed to uninstall node v20.1.1. Check "${NVM_DIR}/versions/node/v20.1.1" for remaining files.' "${TMP_DIR}/stderr" || die "missing uninstall failure message: $(cat "${TMP_DIR}/stderr")"
[ -d "${NVM_DIR}/versions/node/v20.1.1" ] || die 'the version directory should remain'
! nvm_is_version_installed v20.1.1 || die 'the fixture should leave v20.1.1 without its binary'
case "${OUTPUT}" in
  *Uninstalled*) die "a failed uninstall should not report success: ${OUTPUT}" ;;
esac
case "${OUTPUT}" in
  *'Deleted alias one'*) ;;
  *) die "expected the dangling alias to be deleted, got: ${OUTPUT}" ;;
esac
[ ! -f "$(nvm_alias_path)/one" ] || die 'alias one should be removed once its version is gone'
[ "$(nvm_alias two)" = 'v22.1.0' ] || die 'aliases to other versions should be kept'

cleanup
